package com.yycx.module.bus.provider.handler.process;

import com.yycx.bpm.provider.common.handler.ProcessStartHandler;
import com.yycx.bpm.provider.model.ProcessInstanceRequest;
import com.yycx.common.base.utils.FlymeUtils;
import com.yycx.common.constants.CommonConstants;
import com.yycx.common.security.OpenHelper;
import com.yycx.module.bus.client.entity.BusPayment;
import com.yycx.module.bus.provider.service.BusPaymentService;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 市场保证金审核流程
 *
 * @author zyf
 */
@Component
public class CustomBondStartProcessHandler implements ProcessStartHandler {

    @Autowired
    private BusPaymentService paymentService;

    /**
     * 初始化流程参数
     *
     * @param processInstanceRequest
     * @return
     */
    @Override
    public String init(ProcessInstanceRequest processInstanceRequest) {
        Long companyId = OpenHelper.getCompanyId();
        processInstanceRequest.setProcessKey("process_custombond_" + companyId);
        return processInstanceRequest.getBusinessKey();
    }

    /**
     * 设置全局流程变量
     *
     * @param processInstanceRequest
     * @param definition
     * @return
     */
    @Override
    public Map<String, Object> initVariables(ProcessInstanceRequest processInstanceRequest, ProcessDefinition definition) {
        Map<String, Object> map = new HashMap<>();
        BusPayment payment = paymentService.getById(processInstanceRequest.getBusinessKey());
        map.put("deptId", payment.getDeptId());
        map.put("paymentNo", payment.getPaymentNo());
        return map;
    }


    /**
     * 启动完成业务处理
     *
     * @param processInstanceRequest
     * @param definition
     * @param processInstance
     * @param tasks
     * @param variables
     */
    @Override
    public Boolean afterComplete(ProcessInstanceRequest processInstanceRequest, ProcessDefinition definition, ProcessInstance processInstance, List<Task> tasks, Map<String, Object> variables) {
        String businessKey = processInstanceRequest.getBusinessKey();
        //更新资金支付单为已提交并关联流程实例ID
        return paymentService.updatePaymentState(Long.parseLong(businessKey), processInstance.getProcessInstanceId(), CommonConstants.INT_1);
    }
}
